#!/user/python
# -*- coding: utf-8 -*-
from WindPy import *
import sys
import MySQLdb
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

w.start()


# realtime=w.wsq("600000.SH,000001.SZ","rt_last,rt_last_vol")#



def get_yesn(day=4):
    today = datetime.date.today()
    span = datetime.timedelta(days=day)
    someday = today - span
    return someday
    # return datetime.datetime.strptime(yesterday, "%YYYY-%mm-%dd")


def get_today():
    return datetime.date.today()


def update(line):
    db = MySQLdb.connect("192.168.3.14", "root", "123", "phoenix")
    cursor = db.cursor()

    val = str(line)

    insert_sql = "insert into stock_history_info values(" + val[1:len(val) - 1] + ")"

    print(insert_sql)

    try:
        cursor.execute(insert_sql)
        db.commit()
    except:
        db.rollback()
    db.close


def get_one_day(day=get_yesn()):
    for i in range(0, 200):
        name = str(600000 + i)
        data = w.wsd(name + ".SH", "open,high,low,close,vwap,volume,turn", day, day, 'Fill=Previous','PriceAdj=F',showblank=0)
        time = data.Times
        value = data.Data

        if type(value) is list and len(value) > 4:
            col = len(value)
            row = len(value[0])
            for r in range(row):
                line = [name]
                for c in range(col):
                    line.append(str(value[c][r])),
                line.append(str(time[r].date()))
                update(line)
        else:
            print(name, " no data on ", day)

    for i in range(1, 101):
        line = []
        if i < 10:
            name = "00000" + str(i)
        elif i < 100:
            name = "0000" + str(i)
        else:
            name = "000" + str(i)
        data = w.wsd(name + ".SZ", "open,high,low,close,vwap,volume,turn", day, day,
                     "TradingCalendar = SZSE",'Fill=Previous','PriceAdj=F',
                     showblank=0)
        time = data.Times
        value = data.Data
        # print data
        if type(value) is list and len(value) > 4:
            col = len(value)
            row = len(value[0])
            for r in range(row):
                line = [name]
                for c in range(col):
                    line.append(str(value[c][r])),
                line.append(str(time[r].date()))
                update(line)
        else:
            print(name, " no data on ", day)

if __name__ == "__main__":
    today = datetime.date.today()
    span = datetime.timedelta(1)
    #2 days ago,then get_yesn(2)
    tm = get_yesn(770)
    while tm <today:
        if tm.isoweekday() != 6 and tm.isoweekday() != 7:
            get_one_day(tm)
        tm += span
